package com.xiaouyudeguang.common.plugins;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.schema.property.ModelSpecificationFactory;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import javax.persistence.Column;
import javax.persistence.Transient;
import java.util.Optional;

import static springfox.bean.validators.plugins.Validators.annotationFromBean;
import static springfox.bean.validators.plugins.Validators.annotationFromField;

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class ColumnPropertyBuilder implements ModelPropertyBuilderPlugin {
    private final DescriptionResolver descriptions;
    private final ModelSpecificationFactory modelSpecifications;

    @Autowired
    public ColumnPropertyBuilder(
            DescriptionResolver descriptions,
            ModelSpecificationFactory modelSpecifications) {
        this.descriptions = descriptions;
        this.modelSpecifications = modelSpecifications;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void apply(ModelPropertyContext context) {
        Optional<Column> column = extractAnnotation(context);
        if (column.isPresent()) {
            String columnDefinition = column.get().columnDefinition();
            if (columnDefinition.contains("comment")) {
                columnDefinition =  columnDefinition.substring(columnDefinition.indexOf("comment '") + 9);
                columnDefinition = columnDefinition.substring(0, columnDefinition.lastIndexOf("'"));
                context.getSpecificationBuilder().description(columnDefinition);
                context.getBuilder().description(columnDefinition);
            }
        }
    }

    private Optional<Column> extractAnnotation(ModelPropertyContext context) {
        Optional<Transient> optional = annotationFromBean(context, Transient.class)
                .map(Optional::of)
                .orElse(annotationFromField(context, Transient.class));
        if (optional.isPresent()){
            return Optional.empty();
        }
        return annotationFromBean(context, Column.class)
                .map(Optional::of)
                .orElse(annotationFromField(context, Column.class));
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}
